import { hostingStyleStore } from '@/stores/hosting-style-store';
import { storeBindingsBehavior } from 'mobx-miniprogram-bindings';
import { getScheduleInfo } from '@/api/calendar';
import { HOSTING_STYLE_VIDEO_SIZE_LIMIT } from '@/assets/constant/config-constants';
import { getAllComments } from '@/api/comment';
import bus from 'iny-bus';
import { behavior as computedBehavior } from 'miniprogram-computed';

const tabList = ['作品', '档期', '评价'] as const;

let deleteScheduleEventId = '';
let editScheduleEventId = '';

Page({
  behaviors: [storeBindingsBehavior, computedBehavior],
  storeBindings: {
    store: hostingStyleStore,
    fields: ['profile', 'workList'],
    actions: ['getProfile', 'getWorkList', 'updateWorkLikeStatus', 'resetWorkList'],
  },
  data: {
    navBarStyle: '--nav-bar-background-color: #fff0;--nav-bar-icon-color: rgba(255, 255, 255, 0.9);--nav-bar-title-text-color: #0000;',
    navBarHeight: getApp().globalData.CustomBar,
    tabList,
    activeTab: '作品' as (typeof tabList)[number],
    scheduleData: [] as ScheduleDataByYear,
    commentInfo: {
      sf_avg: '',
      commentCount: 0,
    },
    commentList: [],
    commentLabelList: [],
    commentListPagination: {
      page: 1,
      pageSize: 20,
      total: -1,
    },
  },
  computed: {
    addBtnText(data: typeof this.data) {
      return data.activeTab === '作品' ? '上传作品' : '添加档期';
    },
  },
  onLoad() {
    this.getProfile();
    this.getWorkList();
    this.getScheduleDataPerYear();
    this.getCommentList();
    deleteScheduleEventId = bus.on('deleteSchedule', this.getScheduleDataPerYear);
    editScheduleEventId = bus.on('editSchedule', this.getScheduleDataPerYear);
  },
  onUnload() {
    bus.remove('deleteSchedule', deleteScheduleEventId);
    bus.remove('editSchedule', editScheduleEventId);
  },
  async onPullDownRefresh() {
    this.resetWorkList();
    await this.getWorkList();
    wx.stopPullDownRefresh();
  },
  onPageScroll({ scrollTop }) {
    const TARGET_SCROLL_TOP = 140;
    const progress = Math.min(scrollTop / TARGET_SCROLL_TOP, 1);
    const backgroundColor = `rgba(255, 255, 255, ${progress})`;
    const leftIconColorCode = 255 * (1 - progress);

    const leftIconColor = `rgba(${leftIconColorCode}, ${leftIconColorCode}, ${leftIconColorCode}, ${0.9})`;
    const titleColor = `rgba(0, 0, 0, ${progress})`;

    this.setData({
      navBarStyle: `--nav-bar-background-color: ${backgroundColor};--nav-bar-icon-color: ${leftIconColor};--nav-bar-title-text-color: ${titleColor};`,
    });
  },
  onReachBottom() {
    switch (this.data.activeTab) {
      case '作品':
        this.getWorkList();
        break;
      case '档期':
        break;
      case '评价':
        this.getCommentList();
        break;
      default:
        break;
    }
  },
  onClickLeft() {
    wx.navigateBack();
  },
  onClickEditProfile() {
    wx.navigateTo({
      url: '/subpkg/pages/edit-profile/edit-profile',
    });
  },
  onClickWechat() {
    const qrCodePopup = this.selectComponent('#qrCodePopup');
    qrCodePopup.open();
  },
  onClickPhone() {
    wx.makePhoneCall({
      phoneNumber: this.data.profile.host_style_phone,
    });
  },
  onClickTab(event: WechatMiniprogram.Touch) {
    const { tab } = event.currentTarget.dataset;
    this.setData({
      activeTab: tab,
    });
  },
  onLike(e: WechatMiniprogram.CustomEvent) {
    this.updateWorkLikeStatus(e.detail.find_id, true);
  },
  async getScheduleDataPerYear() {
    const {
      data: { list },
    } = await getScheduleInfo('');
    const resScheduleData = list.reverse();
    const yearSet = new Set(resScheduleData.map((item) => item?.date?.split('-')[0]));
    const scheduleData: ScheduleDataByYear = Array.from(yearSet).map((year) => ({
      year: Number(year),
      scheduleDataByMonth: resScheduleData
        .filter((item) => item?.date?.startsWith(year))
        .map((item) => ({
          month: Number(item.date.split('-')[1]),
          scheduleList: item.dataList.map((schedule) => ({
            ...schedule,
            day: Number(schedule.date.split('-')[2]),
          })),
        })),
    }));
    this.setData({
      scheduleData,
    });
  },
  async getCommentList() {
    if (this.data.commentListPagination.total !== -1 && this.data.commentList.length >= this.data.commentListPagination.total) {
      wx.showToast({ title: '没有更多了', icon: 'none' });
      return;
    }
    try {
      const res = await getAllComments({
        currentPage: this.data.commentListPagination.page,
        showCount: this.data.commentListPagination.pageSize,
        is_need_label: '1',
      });
      if (res.code !== 200) {
        throw new Error(res?.msg);
      }

      const labelList = res.data?.labelInfo?.labelList || [];
      const newCommentList = res.data.list.map((item) => ({
        ...item,
        labelList: item.label.split(',').map((labelId) => (labelList.find((label) => label.id.toString() === labelId) || {}).bg_name || ''),
      }));
      this.setData({
        commentInfo: {
          sf_avg: res.data.comment_info?.sf_avg || '',
          commentCount: res.data.totalResult,
        },
        commentList: this.data.commentList.concat(newCommentList),
        commentLabelList: res.data?.labelInfo?.labelList || [],
        'commentListPagination.page': this.data.commentListPagination.page + 1,
        'commentListPagination.total': res.data.totalResult,
      });
    } catch (e: any) {
      wx.showToast({ title: e.message, icon: 'none' });
      console.error(e);
    }
  },
  async toPublishImage() {
    const chosenImgList = (
      await wx.chooseMedia({
        mediaType: ['image'],
      })
    ).tempFiles.map((file) => file.tempFilePath);
    wx.navigateTo({
      url: `/subpkg/pages/publish/publish?type=image&chosenImgList=${JSON.stringify(chosenImgList)}`,
    });
  },
  async toPublishVideo() {
    const chooseMediaRes = await wx.chooseMedia({
      mediaType: ['video'],
    });
    const videoSize = chooseMediaRes.tempFiles[0].size;
    if (videoSize > HOSTING_STYLE_VIDEO_SIZE_LIMIT) {
      wx.showToast({
        title: `视频大小不能超过${HOSTING_STYLE_VIDEO_SIZE_LIMIT / 1024 / 1024}M`,
        icon: 'none',
      });
      return;
    }
    const chosenVideo = chooseMediaRes.tempFiles[0].tempFilePath;
    wx.navigateTo({
      url: '/subpkg/pages/publish/publish?type=video&chosenVideo=' + chosenVideo,
    });
  },
  async onClickAdd() {
    if (this.data.activeTab === '作品') {
      try {
        const { tapIndex } = await wx.showActionSheet({
          itemList: ['图片', '视频'],
        });

        if (tapIndex === 0) {
          this.toPublishImage();
          return;
        }

        this.toPublishVideo();
      } catch (e) {
        console.error('e', e);
      }
      return;
    }

    wx.navigateTo({
      url: '/subpkg/pages/add-schedule/add-schedule',
      events: {
        addScheduleSuccess: () => {
          console.log('addScheduleSuccess');
          this.getScheduleDataPerYear();
        },
      },
    });
  },
});
